/*
 * Created by George on 2014/8/27.
 * APP name: mahoo 入口程序
 *
 * 采用严格 Javascript 方法
 *
 */
'use strict';


/* 模块定义
 * 注明每个模块含义
 */

// Koa 框架
var koa = require('koa');
// HTTP 服务模块
var http = require('http');
// session 管理模块
//var session = require('koa-generic-session');
// redis 存储模块
//var redisStore = require('koa-redis');
// body 模块
//var bodyParser = require('koa-bodyparser');
var bodyParser = require('koa-better-body');
// http的静态文件模块
//var staticCache = require('koa-static-cache');

var jsonp = require('koa-safe-jsonp');

//var Scanner = require('koa-router-scan');//路由扫描
var router = require('koa-router')();
var APIroute = require('../routes/api')(router);
var MANroute = require('../routes/manapi')(router);
var O2Oroute = require('../routes/o2oapi')(router);
var MANO2Oroute = require('../routes/o2oManapi')(router);
var C = require('./../config/index');
var cors = require('koa-cors');//解决跨域

var gzip = require('koa-gzip');//压缩页面

// 实例化 Koa
var app = koa();
app.use(gzip());

// x-response-time
app.use(function *(next) {
  // (1) 进入路由
  var start = new Date;
  this.startAt = start;
  yield next;
  // (5) 再次进入 x-response-time 中间件，记录2次通过此中间件「穿越」的时间
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');
  // (6) 返回 this.body
  midLog.call(this);
});

var midLog = require('../common/logFlow/midLog.js');

app.proxy = false;//do not support `X-Forwarded-*` header from 2015-11-23

app.use(cors({credentials: true}));

app.use(bodyParser());

// Session 名
app.keys = ['keys', 'keykeys'];
//app.use(session({
//  // 默认采用 memory 方式
//  store: new redisStore(),
//    key: C.session.key,
//    prefix: C.session.prefix,
//    ttl: C.session.ttl*1000,
//    cookie : {
//      domain: C.cookie.domain,
//      maxage: C.cookie.maxage
//    }
////    defer: true
//}));

// 注入 router 模块
//app.use(require('koa-trie-router')(app));
//var scanner = new Scanner(app);
//scanner.scan('./routes');


// 设置 HTTP 服务器的缓存时间
//app.use(staticCache(path.join(__dirname, 'public'), {
//app.use(staticCache('./public'), {
// 默认静态文件 cache 7 天
//  maxAge: 0 * 24 * 60 * 60
//});


app.use(router.routes());
//APIroute(app);
//MANroute(app);
//O2Oroute(app);

jsonp(app, {
  callback: '_callback', // default is 'callback'
  limit: 50 // max callback name string length, default is 512
});


var mPubuIM = require('../model/mPubuIM.js');
app.on('error', function (err, ctx) {
  console.error('ERROR ON App.');
  console.error(err);

  //log.error('server error', err, ctx);

  //描述
  let dec = "";
  dec += "err: " + JSON.stringify(err);
  dec += "   ctx.I: " + JSON.stringify(ctx.I);
  dec += "   originalUrl: " + ctx.originalUrl;
  //配置
  let temp = {};
  temp.text = "有错,请留意.";
  temp.title = err.message || "";
  temp.description = dec || "";
  //temp.url = "";
  temp.color = "error";
  //实例
  var pubuIM = new mPubuIM(temp);
  pubuIM.send();

});


module.exports = app;
